home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3856 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: division problem
  5. Date: 31 Jan 96 15:24:23 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.823101863@hubcap>
  8. References: <31097D77.11AA@rain.org> <26JAN199622082450@erich.triumf.ca> <4eh246$u6h@airdmhor.gen.nz> <4ej4ha$66@fountain.mindlink.net> <DLzvGG.2rn@uns.bris.ac.uk>  <Pine.SOL.3.90.960130150923.21923F-100000@flute> <DM1KMy.G3p@uns.bris.ac.uk>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10.  
  11. nathan@pact.srf.ac.uk (Nathan Sidwell) writes:
  12.  
  13. |Darrell Grainger (a378grai@cdf.toronto.edu) wrote:
  14. |: On Tue, 30 Jan 1996, Nathan Sidwell (me) wrote:
  15.  
  16. |: > Still no need to use floating point,
  17. |: > celcius = ((fahrenheit - 32) * 5 + 4) / 9
  18.  
  19. |Adding 4 will give the correct rounding for values >= 0 or if division
  20. |truncates to most neg int.
  21. |Adding 5 will  give incorrect rounding, whatever the domain of the dividend.
  22. |Subtracting 4 gives correct rounding for values < 0 if division rounds
  23. |towards zero.
  24.  
  25. |[...]
  26.  
  27. |For systems where division rounds towards zero, the expression should be
  28.  
  29. |celcius = ((fahrenheit - 32) * 5 + (fahrenheit < 32 ? -4 : 4)) / 9
  30.  
  31. |Depending on the target architecture and the strength of the compiler,
  32. |the conditional expression could be evaluated with bit masking operations.
  33.  
  34. Hmm.  This looks like a job for div()!
  35.  
  36. The oft-neglected div() function has well-defined, portable semantics
  37. for division with negative operands, precisely so that a program does
  38. not have to determine which direction truncation takes--it always
  39. truncates toward zero.  Unfortunately, IMO, this is the less desirable
  40. way to go, precisely because rounding now depends on the sign of the
  41. quotient.  I guess it was intended to mimic FORTRAN's semantics.
  42.  
  43. Thus:
  44.  
  45.     #include <stdlib.h>
  46.  
  47.     celcius = div((fahrenheit - 32) * 5 +
  48.                   (fahrenheit < 32 ? -4 : 4), 9).quot;
  49.  
  50. works on any machine.
  51. -- 
  52.         Matthew Saltzman
  53.         Clemson University Math Sciences
  54.         mjs@clemson.edu
  55.